package com.whzykj.common;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.DbKit;

/**
 * 用于JDBC的原始事务等处理
 * 
 * @author YZH
 * 
 */
public class DbUtil {
	private static Connection conn = null;
	private static Statement stmt = null;
	private static PreparedStatement pstmt = null;
	private static ResultSet rs = null;

	/**
	 * 批量执行SQL语句
	 * @param sqlList
	 * @return
	 */
	public static boolean batch(List<String> sqlList) {
		boolean result = false;
		if(sqlList==null || sqlList.size()==0){
			return false;
		}
		try {
			conn = DbKit.getConfig().getDataSource().getConnection();
			DbKit.getConfig().setThreadLocalConnection(conn);
			conn.setAutoCommit(false); // 将自动提交变成false
			stmt = conn.createStatement();
			for (String sql : sqlList) {
				stmt.addBatch(sql);
			}
			int[] cnt = stmt.executeBatch();
			conn.commit();
			conn.setAutoCommit(true);
			result = true;
		} catch (Exception ex) {
			try {
				if (null != conn)
					conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			result = false;
			throw new ActiveRecordException(ex);
		} finally {
			try {
				if(stmt!=null){
					stmt.close();
				}
				if (null != conn) {
					conn.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			} finally {
				DbKit.getConfig().removeThreadLocalConnection();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
